package com.sangfor.ssl.l3vpn.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import com.sangfor.bugreport.logger.Log;
import com.sangfor.ssl.SangforAuthManager;
import com.sangfor.ssl.common.AsyncTask.AsyncResult;
import com.sangfor.ssl.common.AsyncTask.AsyncTaskCallback;
import com.sangfor.ssl.common.AsyncTask.AsyncTaskState;
import com.sangfor.ssl.common.AsyncTask.AsyncTaskType;
import com.sangfor.ssl.easyapp.SangforAuthForward;
import com.sangfor.ssl.l3vpn.service.LogoutTaskState;
import com.sangfor.ssl.service.setting.GlobalSettingUtils;
import com.sangfor.ssl.service.setting.ResourceManager;
import com.sangfor.ssl.service.setting.SettingManager;
import com.sangfor.ssl.service.setting.SystemConfiguration;
import com.sangfor.ssl.service.timeqry.TimeQryService;
import com.sangfor.ssl.service.utils.IGeneral;
import com.sangfor.ssl.service.utils.network.HttpConnect;
import java.lang.ref.WeakReference;
import java.util.List;

/* loaded from: classes2.dex */
public class L3vpnController extends AsyncTaskCallback implements IVpnStatusChangedListener {
    private static final String TAG = "L3vpnController";
    private static L3vpnController instance;
    private static Handler mHandler;
    private VpnServiceManager mL3vpnManager;
    private WeakReference<Activity> mActivity = null;
    private Context mContext = null;
    private TimeQryService mTimeQueryservice = null;
    private ServiceConnection mTimeQryServiceConnection = null;
    private LogoutTaskState mLogoutTaskState = new LogoutTaskState();

    public static L3vpnController getInstance() {
        if (instance == null) {
            instance = new L3vpnController();
        }
        return instance;
    }

    private L3vpnController() {
    }

    public void register(Activity activity, Handler handler) {
        this.mActivity = new WeakReference<>(activity);
        mHandler = handler;
        this.mContext = activity.getApplicationContext();
        VpnServiceManager vpnServiceManager = VpnServiceManager.getInstance();
        this.mL3vpnManager = vpnServiceManager;
        vpnServiceManager.registerListener(this);
    }

    public boolean initL3VPNService() {
        if (initVpnConf() && initLoginAuthConf() && initConf() && initResource()) {
            Log.info(TAG, "initL3VPNService success!");
            return true;
        }
        return false;
    }

    private boolean initVpnConf() {
        String nGetTwfid = SangforAuthForward.getInstance().nGetTwfid();
        if (TextUtils.isEmpty(nGetTwfid)) {
            Log.info(TAG, "init l3vpn conf failed, twfid is empty");
            return false;
        }
        GlobalSettingUtils.updateTwfid(nGetTwfid);
        String str = (String) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_HOST_KEY);
        HttpConnect httpConnect = new HttpConnect();
        httpConnect.setCookie(str, IGeneral.COOKIE_TWFID_STRING, nGetTwfid);
        httpConnect.setCookie(str, IGeneral.COOKIE_MBTWFID_STRING, nGetTwfid);
        Log.info(TAG, "init l3vpn twfid success");
        return true;
    }

    private boolean initLoginAuthConf() {
        String nGetResultProperty = SangforAuthForward.getInstance().nGetResultProperty(SettingManager.KEY_LOGIN_AUTH_RESULT);
        if (TextUtils.isEmpty(nGetResultProperty)) {
            Log.info(TAG, "init l3vpn conf failed, login auth conf is empty");
            return false;
        } else if (!SystemConfiguration.getInstance().parse(2, nGetResultProperty)) {
            Log.info(TAG, "init l3vpn conf failed, login auth conf parse failed");
            return false;
        } else {
            Log.info(TAG, "init l3vpn login auth conf success");
            return true;
        }
    }

    private boolean initConf() {
        String nGetResultProperty = SangforAuthForward.getInstance().nGetResultProperty(SettingManager.KEY_CONF_RESULT);
        if (TextUtils.isEmpty(nGetResultProperty)) {
            Log.info(TAG, "init l3vpn conf failed, conf.csp info is empty");
            return false;
        } else if (!SystemConfiguration.getInstance().parse(3, nGetResultProperty)) {
            Log.info(TAG, "init l3vpn conf failed, parse conf.csp info failed");
            return false;
        } else {
            Log.info(TAG, "init l3vpn conf.csp info success");
            return true;
        }
    }

    private boolean initResource() {
        String nGetResultProperty = SangforAuthForward.getInstance().nGetResultProperty(SettingManager.KEY_RCLIST_RESULT);
        if (TextUtils.isEmpty(nGetResultProperty)) {
            Log.info(TAG, "init l3vpn conf failed, resource info is empty");
            return false;
        } else if (!ResourceManager.getInstance().parseRcXml(nGetResultProperty)) {
            Log.info(TAG, "init l3vpn conf failed, parse resource info failed");
            return false;
        } else {
            Log.info(TAG, "init l3vpn parse resource info success");
            return true;
        }
    }

    public synchronized void respondShutdown() {
        stopTimeQryThread();
        this.mL3vpnManager.setShutDownStatus(true);
    }

    private void sendLogoutMessage() {
        Message message = new Message();
        message.what = 2;
        message.arg1 = 3;
        message.arg2 = 17;
        Log.info(TAG, "L3vpn send logout message.");
        mHandler.sendMessage(message);
    }

    public void sendStatusChangedMessage(int i) {
        Message message = new Message();
        message.what = 8;
        message.arg1 = 7;
        message.arg2 = i;
        Log.info(TAG, "L3vpn send status changed message. reasonCode: " + i);
        mHandler.sendMessage(message);
    }

    private void sendNormalMessage(int i) {
        Message message = new Message();
        message.what = 2;
        message.arg1 = i;
        Log.info(TAG, "L3vpn send normal message. result: " + i);
        mHandler.sendMessage(message);
    }

    private void sendRebootMessage(String str) {
        Message message = new Message();
        message.what = 2;
        message.arg1 = -6;
        Log.error(TAG, str);
        mHandler.sendMessage(message);
    }

    private void sendErrorMessage(String str) {
        Message message = new Message();
        message.what = 2;
        message.arg1 = -3;
        Log.error(TAG, str);
        mHandler.sendMessage(message);
    }

    public void sendTunnelOKMessage(int i) {
        Message message = new Message();
        message.what = 2;
        message.arg1 = 2;
        message.arg2 = 100;
        mHandler.sendMessage(message);
    }

    private void sendReloginMessage() {
        Message message = new Message();
        message.what = 6;
        Log.info(TAG, "L3vpn send relogin message.");
        mHandler.sendMessage(message);
    }

    public static void quit() {
        instance = null;
    }

    public boolean isIsolationEnable() {
        return SystemConfiguration.getInstance().isIsolationEnable();
    }

    public boolean startVpnService(Context context) throws IllegalStateException {
        LaunchMode launchMode;
        LaunchMode launchMode2 = LaunchMode.LAUNCH_TYPE_LAST;
        if (isIsolationEnable()) {
            launchMode = LaunchMode.NET_TYPE_ISOLATION;
        } else {
            launchMode = LaunchMode.NET_TYPE_VPN;
        }
        return startVpnService(context, launchMode, LoginState.LOGIN_STATE_ONLINE);
    }

    private boolean startVpnService(Context context, LaunchMode launchMode, LoginState loginState) throws IllegalStateException {
        if (this.mL3vpnManager.prepare(context) != null) {
            throw new IllegalStateException("vpnservice permission is not enable, please request permission.");
        }
        int i = AnonymousClass1.$SwitchMap$com$sangfor$ssl$l3vpn$service$LoginState[loginState.ordinal()];
        if (i == 1) {
            Log.info(TAG, "LOGIN_STATE_ONLINE");
        } else if (i == 2) {
            Log.info(TAG, "LOGIN_STATE_OFFLINE");
        }
        Intent intent = new Intent(context, EasyappSvpnService.class);
        intent.putExtra(VpnServiceManager.LAUNCH_TYPE_KEY, launchMode.intValue());
        intent.putExtra(VpnServiceManager.LOGIN_STATE_KEY, loginState.intValue());
        if (Build.VERSION.SDK_INT >= 26) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
        return true;
    }

    public boolean updateVpnServiceState(LoginState loginState) {
        if (this.mContext == null) {
            Log.error(TAG, "svpnLogout exec failed,please check that your code is initialized before updateVpnServiceState!!");
            return false;
        }
        Log.info(TAG, "update vpn service state:" + loginState.name());
        if (isIsolationEnable()) {
            startVpnService(this.mContext, LaunchMode.NET_TYPE_ISOLATION, loginState);
            return true;
        }
        startVpnService(this.mContext, LaunchMode.NET_TYPE_VPN, loginState);
        return true;
    }

    public synchronized void svpnLogout(LogoutTaskState.LogoutType logoutType) {
        if (this.mContext == null) {
            Log.error(TAG, "svpnLogout exec failed,please check that your code is initialized before logging out!!");
            return;
        }
        Log.info(TAG, "svpn logout, logoutType:" + logoutType.name());
        this.mLogoutTaskState.taskState = AsyncTaskState.TASK_PRE_EXECUTED;
        stopTimeQryThread();
        Intent intent = new Intent(IGeneral.SERVICE_ACTION_TIMEQRY);
        intent.setPackage(this.mContext.getPackageName());
        this.mContext.stopService(intent);
        this.mLogoutTaskState.logoutType = logoutType;
        new LogoutTask(this).executeOnExecutor(SangforAuthManager.VPN_AUTH_TASK_EXECUTOR, new Void[0]);
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes2.dex */
    public static class LogoutTask extends AsyncTask<Void, Void, Void> {
        private AsyncTaskCallback mCallback;

        LogoutTask(AsyncTaskCallback asyncTaskCallback) {
            this.mCallback = asyncTaskCallback;
        }

        @Override // android.os.AsyncTask
        protected void onPreExecute() {
            super.onPreExecute();
            Log.info(L3vpnController.TAG, "Start logout task.");
            this.mCallback.onTaskStart(AsyncTaskType.TYPE_LOGOUT);
        }

        /* JADX INFO: Access modifiers changed from: protected */
        @Override // android.os.AsyncTask
        public Void doInBackground(Void... voidArr) {
            this.mCallback.onTaskRunning(AsyncTaskType.TYPE_LOGOUT);
            if (Build.VERSION.SDK_INT >= 14) {
                VpnServiceManager.getInstance().stopService();
            }
            SangforAuthForward.getInstance().nVpnLogout(false);
            return null;
        }

        /* JADX INFO: Access modifiers changed from: protected */
        @Override // android.os.AsyncTask
        public void onPostExecute(Void r3) {
            super.onPostExecute((LogoutTask) r3);
            Log.info(L3vpnController.TAG, "Logout task finish." + Log.getTimestamp());
            this.mCallback.onTaskFinish(AsyncTaskType.TYPE_LOGOUT, null);
        }

        @Override // android.os.AsyncTask
        protected void onCancelled() {
            super.onCancelled();
            this.mCallback.onTaskCancel(AsyncTaskType.TYPE_LOGOUT);
        }
    }

    private void bindTimeQueryService() {
        if (this.mTimeQryServiceConnection != null) {
            startTimeQryThread();
        } else if (this.mContext == null) {
            Log.error(TAG, "svpnLogout exec failed,please check that your code is initialized before bindTimeQueryService!!");
        } else {
            this.mTimeQryServiceConnection = new TimeQueryServiceConnection(this, null);
            Intent intent = new Intent(IGeneral.SERVICE_ACTION_TIMEQRY);
            intent.setPackage(this.mContext.getPackageName());
            if (this.mContext.bindService(intent, this.mTimeQryServiceConnection, 1)) {
                return;
            }
            Log.warn(TAG, "fail to bind Service");
        }
    }

    private void unbindTimeQueryService() {
        Context context = this.mContext;
        if (context == null) {
            Log.error(TAG, "svpnLogout exec failed,please check that your code is initialized before unbindTimeQueryService!!");
            return;
        }
        ServiceConnection serviceConnection = this.mTimeQryServiceConnection;
        if (serviceConnection != null) {
            context.unbindService(serviceConnection);
            this.mTimeQryServiceConnection = null;
        }
    }

    public boolean isNeedVpnService(StringBuilder sb) {
        sb.setLength(0);
        if (!SystemConfiguration.getInstance().isL3vpnServiceSupported()) {
            sb.append("只支持Android4.0及以上的手机");
            return false;
        } else if (SystemConfiguration.getInstance().isVpnLineEnable() || ResourceManager.getInstance().containL3vpnRc()) {
            return true;
        } else {
            sb.append("VPN服务端没有配置L3VPN资源");
            return false;
        }
    }

    public void handleL3VpnService() {
        if (this.mContext == null) {
            Log.error(TAG, "svpnLogout exec failed,please check that your code is initialized before handleL3VpnService!!");
            return;
        }
        Log.info(TAG, "handle vpn service");
        startVpnService(this.mContext);
    }

    @Override // com.sangfor.ssl.l3vpn.service.IVpnStatusChangedListener
    public void onVpnStatusChanged(VpnStatus vpnStatus, int i) {
        SangforAuthForward.getInstance();
        SangforAuthForward.vpnStatusCallback(vpnStatus.intValue());
        if (vpnStatus == VpnStatus.VPN_STATUS_CONNECTED) {
            Log.info(TAG, "cur vpnstatus is connected!");
            sendTunnelOKMessage(100);
        }
        if (vpnStatus == VpnStatus.VPN_STATUS_DISCONNECTED) {
            Log.info(TAG, "cur vpnstatus is disconnected! status change code=" + i);
            if (i == 31) {
                sendErrorMessage("Start SvpnService failed!");
            } else if (i == 32) {
                sendRebootMessage("system VpnService start failed, need reboot your phone!");
            } else if (i != 35) {
                switch (i) {
                    case 4:
                        sendErrorMessage("service ip conflict!");
                        return;
                    case 5:
                        sendErrorMessage("service ip shortage!");
                        return;
                    case 6:
                        sendErrorMessage("service ip kicked!");
                        return;
                    case 7:
                        sendErrorMessage("service ip other error!");
                        return;
                    case 8:
                        Log.info(TAG, "Receive shutdown command!");
                        respondShutdown();
                        return;
                    case 9:
                        Log.info(TAG, "service recv virIP!");
                        sendNormalMessage(5);
                        return;
                    case 10:
                        Log.info(TAG, "service ip reset!");
                        return;
                    case 11:
                        Log.info(TAG, "service ip reconnect!");
                        return;
                    case 12:
                        Log.info(TAG, "service native exit!");
                        return;
                    default:
                        Log.info(TAG, "Ignore invalid signal! + errcode=" + i);
                        return;
                }
            } else {
                boolean booleanValue = ((Boolean) SettingManager.getInstance().getGlobalValue(SettingManager.GLOBAL_SHUTDOWN_STATE, false)).booleanValue();
                if (booleanValue) {
                    SettingManager.getInstance().setGlobalValue(SettingManager.GLOBAL_SHUTDOWN_STATE, false);
                    sendReloginMessage();
                    return;
                }
                Log.info(TAG, "Relogining ShutDown=" + booleanValue);
            }
        }
    }

    @Override // com.sangfor.ssl.l3vpn.service.IVpnStatusChangedListener
    public void onPermissionRevoke() {
        Log.info(TAG, "Vpn permission revoke");
        getInstance().svpnLogout(LogoutTaskState.LogoutType.VPN_REVOKE_LOGOUT);
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.sangfor.ssl.l3vpn.service.L3vpnController$1  reason: invalid class name */
    /* loaded from: classes2.dex */
    public static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$com$sangfor$ssl$common$AsyncTask$AsyncTaskType;
        static final /* synthetic */ int[] $SwitchMap$com$sangfor$ssl$l3vpn$service$LoginState;

        static {
            int[] iArr = new int[AsyncTaskType.values().length];
            $SwitchMap$com$sangfor$ssl$common$AsyncTask$AsyncTaskType = iArr;
            try {
                iArr[AsyncTaskType.TYPE_LOGOUT.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            int[] iArr2 = new int[LoginState.values().length];
            $SwitchMap$com$sangfor$ssl$l3vpn$service$LoginState = iArr2;
            try {
                iArr2[LoginState.LOGIN_STATE_ONLINE.ordinal()] = 1;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$sangfor$ssl$l3vpn$service$LoginState[LoginState.LOGIN_STATE_OFFLINE.ordinal()] = 2;
            } catch (NoSuchFieldError unused3) {
            }
        }
    }

    @Override // com.sangfor.ssl.common.AsyncTask.AsyncTaskCallback
    public void onTaskStart(AsyncTaskType asyncTaskType) {
        super.onTaskStart(asyncTaskType);
        if (AnonymousClass1.$SwitchMap$com$sangfor$ssl$common$AsyncTask$AsyncTaskType[asyncTaskType.ordinal()] != 1) {
            return;
        }
        this.mLogoutTaskState.taskState = AsyncTaskState.TASK_STARTED;
    }

    @Override // com.sangfor.ssl.common.AsyncTask.AsyncTaskCallback
    public void onTaskFinish(AsyncTaskType asyncTaskType, AsyncResult asyncResult) {
        super.onTaskFinish(asyncTaskType, asyncResult);
        if (AnonymousClass1.$SwitchMap$com$sangfor$ssl$common$AsyncTask$AsyncTaskType[asyncTaskType.ordinal()] != 1) {
            return;
        }
        this.mLogoutTaskState.taskState = AsyncTaskState.TASK_FINISHED;
        handleLogoutTaskResult();
    }

    public boolean checkManifest() {
        if (this.mContext == null) {
            Log.error(TAG, "svpnLogout exec failed,please check that your code is initialized before checkManifest!!");
            return false;
        }
        try {
            List<ResolveInfo> queryIntentServices = this.mContext.getPackageManager().queryIntentServices(new Intent(this.mContext, EasyappSvpnService.class), 0);
            if (queryIntentServices != null && !queryIntentServices.isEmpty()) {
                if (!IGeneral.SERVICE_VPNSERVICE_PERMISSION.equals(queryIntentServices.get(0).serviceInfo.permission)) {
                    Log.error(TAG, "in AndroidManifest.xml EasyappSvpnService not declare android.permission.BIND_VPN_SERVICE");
                    return false;
                }
                queryIntentServices.clear();
                List<ResolveInfo> queryIntentServices2 = this.mContext.getPackageManager().queryIntentServices(new Intent(this.mContext, TimeQryService.class), 0);
                if (queryIntentServices2 == null || queryIntentServices2.isEmpty()) {
                    Log.error(TAG, "in AndroidManifest.xml not declare TimeQryService!");
                    return false;
                }
                return true;
            }
            Log.error(TAG, "in AndroidManifest.xml not declare EasyappSvpnService!");
            return false;
        } catch (Exception e) {
            Log.error(TAG, "checkManifest failed!", e);
            return true;
        }
    }

    public boolean startVPNBusiness() {
        if (checkManifest()) {
            SettingManager.getInstance().setGlobalValue(SettingManager.GLOBAL_SHUTDOWN_STATE, false);
            this.mL3vpnManager.init(this.mContext);
            StringBuilder sb = new StringBuilder("");
            if (isNeedVpnService(sb)) {
                Intent prepare = this.mL3vpnManager.prepare(this.mContext);
                if (prepare == null) {
                    bindTimeQueryService();
                    handleL3VpnService();
                } else {
                    Activity activity = this.mActivity.get();
                    if (activity == null) {
                        Log.info(TAG, "onL3vpn, activity weakReference get null");
                        return false;
                    }
                    try {
                        ActivityInfo activityInfo = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0);
                        Log.info(TAG, "Activity launchMode:" + activityInfo.launchMode);
                        if (activityInfo.launchMode == 3) {
                            Log.info(TAG, "L3VPN startActivityForResult launchMode should not be singleInstance!!!!");
                            return false;
                        }
                        activity.startActivityForResult(prepare, 1);
                    } catch (Exception e) {
                        Log.info(TAG, "get activity launchMode failed.");
                        e.printStackTrace();
                        return false;
                    }
                }
                return true;
            }
            if (sb.toString().equals("")) {
                sendErrorMessage("onL3vpn, can't support l3vpn");
            } else {
                sendErrorMessage("onL3vpn, can't support l3vpn, " + sb.toString());
            }
            return false;
        }
        return false;
    }

    private void handleLogoutTaskResult() {
        Log.debug(TAG, "clear all http cookies");
        HttpConnect.initializeCookies();
        SettingManager settingManager = SettingManager.getInstance();
        GlobalSettingUtils.updateTwfid("");
        settingManager.set(SettingManager.TWFID_LOGOUT, true);
        SystemConfiguration.isAbleWork = false;
        ResourceManager.isAbleWork = false;
        SettingManager.isAbleWork = false;
        unbindTimeQueryService();
        Log.info(TAG, "logout complete!");
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* loaded from: classes2.dex */
    public class TimeQueryServiceConnection implements ServiceConnection {
        private TimeQueryServiceConnection() {
        }

        /* synthetic */ TimeQueryServiceConnection(L3vpnController l3vpnController, AnonymousClass1 anonymousClass1) {
            this();
        }

        @Override // android.content.ServiceConnection
        public void onServiceDisconnected(ComponentName componentName) {
            L3vpnController.this.mTimeQueryservice = null;
            Log.info(L3vpnController.TAG, "TimeQry onService Disconnected");
        }

        @Override // android.content.ServiceConnection
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            L3vpnController.this.mTimeQueryservice = ((TimeQryService.TimeQryBinder) iBinder).getService();
            Log.info(L3vpnController.TAG, "TimeQry onService Connected");
            L3vpnController.this.startTimeQryThread();
        }
    }

    public void startTimeQryThread() {
        TimeQryService timeQryService = this.mTimeQueryservice;
        if (timeQryService == null) {
            Log.error(TAG, "TimeQuery IBinder service is null.");
        } else {
            timeQryService.startThread();
        }
    }

    public void stopTimeQryThread() {
        TimeQryService timeQryService = this.mTimeQueryservice;
        if (timeQryService == null) {
            Log.error(TAG, "TimeQuery IBinder service is null.");
        } else {
            timeQryService.stopThread();
        }
    }

    public void sendTimeQuery() {
        TimeQryService timeQryService = this.mTimeQueryservice;
        if (timeQryService == null) {
            Log.error(TAG, "TimeQuery IBinder service is null.");
        } else {
            timeQryService.setTurboMode(true);
        }
    }
}
